<?php

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2015/12/7
 * Time: 16:52
 */
include_once(dirname(__FILE__).'/lxbase.class.php');
include_once(ROOTDIR.'include/aopclient.class.php');
class Ap extends Lxbase
{
    //支付宝公钥
    public $alipay_public_key = "-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDDI6d306Q8fIfCOaTXyiUeJHkr
IvYISRcc73s3vF1ZT7XN8RNPwJxo8pWaJMmvyTn9N4HQ632qJBVHf8sxHi/fEsra
prwCtzvzQETrNRwVxLO5jVmRGi60j8Ue1efIlzPXV9je9mkjzOmdssymZkh2QhUr
CmZYI/FCEa3/cNMW0QIDAQAB
-----END PUBLIC KEY-----";
    //字符集
    public $charset = "GBK";

    //获取用户服务窗信息
    public function getapinfo($userid = '')
    {
        //获取用户企悦ID
        if(empty($userid)){$userid=$this->userinfo['userid'];}
        $view=$this->viewdata("*","apuser","where userid={$userid}");
//        var_dump($view);
        if(empty($view)){
            die(jsfshow('没有找到用户服务窗信息，请在支付宝服务设置中配置服务窗信息'));
            exit;
        }
        return $view;
    }

    /**
     * 公用函数-------------------------------------start--------------------------------------------------
     */
    //写入日志
    public function writeLog($text) {
        // $text=iconv("GBK", "UTF-8//IGNORE", $text);
        $text = $this->characet ( $text );
        file_put_contents ( dirname ( __FILE__ ) . "/log/log.txt", date ( "Y-m-d H:i:s" ) . "  " . $text . "\r\n", FILE_APPEND );
    }

    //转换编码
    public function characet($data) {
        if (! empty ( $data )) {
            $fileType = mb_detect_encoding ( $data, array (
                'UTF-8',
                'GBK',
                'GB2312',
                'LATIN1',
                'BIG5'
            ) );
            if ($fileType != 'UTF-8') {
                $data = mb_convert_encoding ( $data, 'UTF-8', $fileType );
            }
        }
        return $data;
    }

    /**
     * 使用SDK执行接口请求
     * @param unknown $request
     * @param string $token
     * @return Ambigous <boolean, mixed>
     */
    public function aopclient_request_execute($request, $config, $token = NULL) {

        $aop = new aop ();
        $aop->appId = $config ['appid'];
        $aop->rsaPrivateKeyFilePath = $config['merchant_private_key'];

        $result = $aop->execute ($request, $token );

        //writeLog("response: ".var_export($result,true));
        return $result;
    }

    /**
     * 公用函数--------------------------------------end--------------------------------------------------
     */

    /**
     * 接口函数--------------------------------------start--------------------------------------------------
     */


    /**
     * 接口函数-------------------------------------end--------------------------------------------------
     */

    /**
     * 请求函数------------------------------------start---------------------------------------------------
     */
    public function sendPostRequst($url, $data) {
        $postdata = http_build_query ( $data );
// 		print_r($postdata);
        $opts = array (
            'http' => array (
                'method' => 'POST',
                'header' => 'Content-type: application/x-www-form-urlencoded',
                'content' => $postdata
            )
        );

        $context = stream_context_create ( $opts );

        $result = file_get_contents ( $url, false, $context );
        return $result;
    }

    //获取参数
    public function getRequest($key) {
        $request = null;
        if (isset ( $_GET [$key] ) && ! empty ( $_GET [$key] )) {
            $request = $_GET [$key];
        } elseif (isset ( $_POST [$key] ) && ! empty ( $_POST [$key] )) {
            $request = $_POST [$key];
        }
        return $request;
    }

    /**
     * 请求函数-------------------------------------end---------------------------------------------------
     */

    /**
     * 支付签名函数---------------------------------start-----------------------------------------------------
     */
    //私钥签名处理
    public function rsa_sign($data, $rsaPrivateKeyFilePath) {
        $priKey = $rsaPrivateKeyFilePath;
        $res = openssl_get_privatekey ( $priKey );
        openssl_sign ( $data, $sign, $res );
        openssl_free_key ( $res );
        $sign = base64_encode ( $sign );
        return $sign;
    }

    //签名请求
    public function sign_request($params, $rsaPrivateKeyFilePath) {
        return $this->rsa_sign ( $this->getSignContent ( $params ), $rsaPrivateKeyFilePath );
    }

    //签名响应
    public function sign_response($bizContent, $charset, $rsaPrivateKeyFilePath) {

        $sign = $this->rsa_sign ( $bizContent, $rsaPrivateKeyFilePath );

        $response = "<?xml version=\"1.0\" encoding=\"$charset\"?><alipay><response>$bizContent</response><sign>$sign</sign><sign_type>RSA</sign_type></alipay>";

        return $response;
    }

    //公钥验证
    public function rsa_verify($data, $sign, $rsaPublicKeyFilePath) {

        // 读取公钥文件
        $pubKey =  $rsaPublicKeyFilePath;

        // 转换为openssl格式密钥
        $res = openssl_get_publickey ( $pubKey );

        // 调用openssl内置方法验签，返回bool值
        $result = ( bool ) openssl_verify ( $data, base64_decode ( $sign ), $res );

        // 释放资源
        openssl_free_key ( $res );

        return $result;
    }

    // 返回公钥验证结果
    public function rsaCheckV2($params, $rsaPublicKeyFilePath) {
        $sign = $params ['sign'];
//        $params ['sign'] = null;
        unset($params ['sign']);
        unset($params ['g']);
        unset($params ['m']);
        unset($params ['a']);
        unset($params ['userid']);

        return $this->rsa_verify ( $this->getSignContent ( $params ), $sign, $rsaPublicKeyFilePath );
    }

    //获取签名内容
    protected function getSignContent($params) {
        ksort ( $params );

        $stringToBeSigned = "";
        $i = 0;
        foreach ( $params as $k => $v ) {
            if (false === $this->checkEmpty ( $v ) && "@" != substr ( $v, 0, 1 )) {
                if ($i == 0) {
                    $stringToBeSigned .= "$k" . "=" . "$v";
                } else {
                    $stringToBeSigned .= "&" . "$k" . "=" . "$v";
                }
                $i ++;
            }
        }
        unset ( $k, $v );

        return $stringToBeSigned;
    }

    /**
     * 校验$value是否非空
     * if not set ,return true;
     * if is null , return true;
     */
    protected function checkEmpty($value) {
        if (! isset ( $value ))
            return true;
        if ($value === null)
            return true;
        if (trim ( $value ) === "")
            return true;

        return false;
    }

    //获取公钥字符串
    public function getPublicKeyStr($pub_pem_path) {
        $content = $pub_pem_path ;
        $content = str_replace ( "-----BEGIN PUBLIC KEY-----", "", $content );
        $content = str_replace ( "-----END PUBLIC KEY-----", "", $content );
        $content = str_replace ( "\r", "", $content );
        $content = str_replace ( "\n", "", $content );
        return $content;
    }

    /**
     * 支付签名函数------------------------------------end--------------------------------------------------
     */


}